// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls

import Fk
import Fk.Components.LunarLTK

ColumnLayout {
  id: root
  anchors.fill: parent
  property var extra_data: ({ name: "", data: [] })
  signal finish()

  BigGlowText {
    Layout.fillWidth: true
    Layout.preferredHeight: childrenRect.height + 4

    text: Lua.tr(extra_data.name)
  }

  ListView {
    id: areaListView
    Layout.fillWidth: true
    Layout.fillHeight: true
    clip: true
    spacing: 10

    model: extra_data.data

    delegate: RowLayout {
      spacing: 15
      // visible: areaCards.count > 0
      width: areaListView.width

      Rectangle {
        border.color: "#A6967A"
        radius: 5
        color: "transparent"
        width: 18
        height: 130
        Layout.alignment: Qt.AlignTop

        Text {
          color: "#E4D5A0"
          text: Lua.tr(cardRepeater.areaName)
          anchors.fill: parent
          wrapMode: Text.WrapAnywhere
          verticalAlignment: Text.AlignVCenter
          horizontalAlignment: Text.AlignHCenter
          font.pixelSize: 15
        }
      }

      // 区域内的卡牌网格
      GridView {
        id: cardGridView
        Layout.fillWidth: true
        Layout.preferredHeight: Math.min(cellHeight * Math.ceil(cardRepeater.count / Math.floor(width / cellWidth)), 
                                        cellHeight * 3) // 最多显示3行，超出可滚动
        cellWidth: 93 + 4
        cellHeight: 130 + 4
        clip: true
        interactive: false // 禁用GridView自身的滚动，使用外部ListView

        model: cardRepeater.count > 0 ? cardRepeater.count : 0

        delegate: CardItem {
          id: cardItem
          autoBack: false
          Component.onCompleted: {
            let cardInfo = cardRepeater.getCardData(index);
            let data = {}
            if (typeof cardInfo === "string") {
              data.cid = 0;
              data.name = cardInfo;
              data.suit = '';
              data.number = 0;
              data.color = '';
            } else if (typeof cardInfo === "object")  {
              data = Lua.call("GetCardData", cardInfo.cid);
              for (let k in cardInfo) {
                data[k] = cardInfo[k]
              }
            } else {
              data = Lua.call("GetCardData", cardInfo);
            }
            setData(data);
          }
        }
      }

      // 用于存储和提供卡牌数据的Repeater
      Repeater {
        id: cardRepeater
        property string areaName: modelData[0] // 区域名字
        
        model: modelData.length - 1 // 减去区域名字
        
        // 辅助函数获取卡牌数据
        function getCardData(idx) {
          return modelData[idx + 1]; // 跳过第一个元素（区域名字）
        }
        
        // 这个Repeater不创建可视元素，只用于数据管理
        delegate: Item { visible: false }
      }
    }
  }
}